﻿using UnityEngine;

namespace CWM.Skinn
{
    public static partial class SkinnEx
    {
        public static class TextureSampler
        {
            private static Texture2D sampleTexture = null;
            private static Texture2D GetSampleTexture(int width, int height)
            {
                if (!sampleTexture)
                {
                    sampleTexture = new Texture2D(width, height)
                    {
                        name = "SampleTexture",
                        hideFlags = HideFlags.HideAndDontSave
                    };
                }
                else
                {
                    if (sampleTexture.width != width || sampleTexture.height != height)
                    {
                        sampleTexture = new Texture2D(width, height)
                        {
                            name = "SampleTexture",
                            hideFlags = HideFlags.HideAndDontSave
                        };
                    }
                }
                return sampleTexture;
            }

            public static Texture2D SampledTexture(Texture texture)
            {
                sampleTexture = GetSampleTexture(texture.width, texture.height);
                RenderTexture active = RenderTexture.active;
                RenderTexture temp = RenderTexture.GetTemporary(texture.width, texture.height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Linear);
                RenderTexture.active = temp;
                Graphics.Blit(texture, temp);
                sampleTexture.ReadPixels(new Rect(0, 0, texture.width, texture.height), 0, 0);
                sampleTexture.Apply();
                RenderTexture.active = active;
                RenderTexture.ReleaseTemporary(temp);
                return sampleTexture;
            }

            public static void Destory()
            {
                if (Application.isEditor) Object.DestroyImmediate(sampleTexture);
                else Object.Destroy(sampleTexture);
            }
        }
    }
}